package com.sgb.jicai.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import com.sgb.jicai.R;
import com.sgb.jicai.base.JiCaiBaseApi;
import com.sgb.jicai.databinding.ActivityFactoryJicaiBinding;
import com.sgb.jicai.entity.JcMyFactoryListEntity;
import com.sgb.jicai.view.adapter.JcMyFactoryAdapter;
import com.sgb.jicai.viewmodel.FactoryJiCaiModel;
import com.swgk.core.base.AppActivity;
import com.swgk.core.util.DisplayUtil;
import com.swgk.core.util.LogUtil;
import com.sgb.jicai.entity.JcCountEntity;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.ButtonClickUtils;
import com.swgk.core.xrecyclerview.XRecyclerView;
import java.util.ArrayList;
import java.util.List;
/**
 * 个人中心——集采管理——供方发起
 */
public class FactoryJicaiActivity extends AppActivity {

    FactoryJiCaiModel model;
    ActivityFactoryJicaiBinding binding;
    private List<String> typeDatas = new ArrayList<>();//Title
    private int page = 1;
    private boolean isLoadMore = false;
    private JcMyFactoryAdapter adapter;
    private int status = 0;
    private int STATUSTYPE = 12;

    public static void start(Context context) {
        Intent intent = new Intent(context, FactoryJicaiActivity.class);
        context.startActivity(intent);
    }
    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_factory_jicai);
        model = new ViewModelProvider(this).get(FactoryJiCaiModel.class);
        binding.ivBack.setOnClickListener(this::onMultiClick);
        binding.tvSearch.setOnClickListener(this::onMultiClick);
        binding.publishSupplier.setOnClickListener(this::onMultiClick);
        if (adapter == null) {
            adapter = new JcMyFactoryAdapter(getActivity(), null);
        }
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getData();
            }

            @Override
            public void onLoadMore() {
                if (model.hasNext) {
                    isLoadMore = true;
                    page = page + 1;
                    model.getList(FactoryJicaiActivity.this,status, page, binding.editSearch.getText().toString().trim());
                } else {
                    binding.recyclerView.loadMoreComplete();
                }
            }
        });
        binding.recyclerView.setAdapter(adapter);

        adapter.setOnItemClick(new AdapterOnItemClick<JcMyFactoryListEntity>() {
            @Override
            public void onItemClick(JcMyFactoryListEntity entity, int position) {
                model.getH5Url(FactoryJicaiActivity.this,entity);
            }
        });
        adapter.setDeleteListener(new JcMyFactoryAdapter.DeleteListerner() {
            @Override
            public void stopJc(JcMyFactoryListEntity entity) {
                String msg = "您确认停止此次集采？";
                new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                        .setTitle("温馨提示")
                        .setMsg(msg)
                        .setDialogCallBack(new CommonDialog.DialogCallBack() {
                            @Override
                            public void onRightClick() {
                                //停止集采
                                model.stopJiCai(FactoryJicaiActivity.this,entity);
                            }

                            @Override
                            public void onLeftClick() {
                            }
                        }).show();
            }

            @Override
            public void DeleteJc(JcMyFactoryListEntity entity) {
                String msg = "将永久删除该条数，还要继续吗？";
                new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                        .setTitle("温馨提示")
                        .setMsg(msg)
                        .setDialogCallBack(new CommonDialog.DialogCallBack() {
                            @Override
                            public void onRightClick() {
                                //删除报价信息接口
                                model.deleteFactory(FactoryJicaiActivity.this,entity.getNo());
                            }
                            @Override
                            public void onLeftClick() {

                            }
                        }).show();
            }


        });

        binding.editSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
//                    if (TextUtils.isEmpty(binding.etView.getText().toString())) {
//                        MToast.showToast(FactoryJicaiActivity.this, "请输入关键字");
//                        return true;
//                    }
                    getData();
                    hideKeyboard();
                }
                return false;
            }
        });
    }

    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_search) {
            getData();
            hideKeyboard();
        } else if (id == R.id.publish_supplier) {
            if (ButtonClickUtils.isFastClick()) {
                // 进行点击事件后的逻辑操作
                startActivityForResult(new Intent(this, JiCaiSupplierPublishAct.class), STATUSTYPE);
            }
        }
    }

    @Override
    protected void init() {
        initTitle();
        initData();
    }

    private void initTitle() {
        setTypeDatas();
    }

    public void initData() {
        getData();
        getTabNum();
    }

    public void setTypeDatas() {
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        setTabTitleSize(binding.tabLayout.getTabAt(0), "全部" + " (0)");
        setTabTitleSize(binding.tabLayout.getTabAt(1), "审批中" + " (0)");
        setTabTitleSize(binding.tabLayout.getTabAt(2), "集采中" + " (0)");
        setTabTitleSize(binding.tabLayout.getTabAt(3), "已拒绝" + " (0)");
        setTabTitleSize(binding.tabLayout.getTabAt(4), "集采完成" + " (0)");

        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()){
                    case 0://全部
                        status = 0;
                        break;
                    case 1://审批中
                        status = 8;
                        break;
                    case 2://集采中
                        status = 1;
                        break;
                    case 3://已拒绝
                        status = 9;
                        break;
                    case 4://集采完成
                        status = 2;
                        break;
                }
                getData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void setTabTitleSize(TabLayout.Tab tab, String text) {
        int start = text.indexOf("(");
        int end = text.length();
        SpannableString textSpan = new SpannableString(text);
        textSpan.setSpan(new AbsoluteSizeSpan(DisplayUtil.sp2px(this, 14)), 0, start, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        textSpan.setSpan(new AbsoluteSizeSpan(DisplayUtil.sp2px(this, 10)), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        tab.setText(textSpan);
    }

    public void getData() {
        isLoadMore = false;
        page = 1;
        model.getList(FactoryJicaiActivity.this,status, page, binding.editSearch.getText().toString().trim());
    }

    public void showList(List<JcMyFactoryListEntity> list, boolean hasNext) {
        binding.recyclerView.refreshComplete();
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() > 0) {
                adapter.addDatas(list);
            } else {
//                binding.recyclerView.setLoadingMoreEnabled(false);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
            binding.emptyView.setVisibility(View.GONE);
        } else {
            binding.recyclerView.refreshComplete();
            if (list.size() > 0) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                adapter.setDatas(list);
//                binding.recyclerView.setLoadingMoreEnabled(true);
            } else {
                adapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
        //设置是否可加载更多：
        if (adapter.getCount() >= 3) {
            binding.recyclerView.setNoMore(!hasNext);
        } else {
            binding.recyclerView.setLoadingMoreEnabled(hasNext);
        }
        getTabNum();
    }

    public void showUrl(String url) {
        JiCaiBaseApi.startWeb(getActivity(), url);
    }

    //更新标题数字
    public void getTabNum() {
        model.getMyOfferBuyListCount(FactoryJicaiActivity.this,binding.editSearch.getText().toString().trim());
    }

    public void setTabNum(List<JcCountEntity> numList) {
        if (null == numList || numList.size() == 0) {
            return;
        }
        for (JcCountEntity entity : numList) {
            try {
                String num = " (" + (Integer.valueOf(entity.getCount()) > 99 ? "99+" : entity.getCount()) + ")";
                switch (Integer.valueOf(entity.getStatus())) {//0、1、2、3、4
                    case 0://全部
                        setTabTitleSize(binding.tabLayout.getTabAt(0), "全部" + num);
                        break;
                    case 8://审批中
                        setTabTitleSize(binding.tabLayout.getTabAt(1), "审批中" + num);
                        break;
                    case 1://集采中
                        setTabTitleSize(binding.tabLayout.getTabAt(2), "集采中" + num);
                        break;
                    case 9://已拒绝
                        setTabTitleSize(binding.tabLayout.getTabAt(3), "已拒绝" + num);
                        break;
                    case 2://集采完成
                        setTabTitleSize(binding.tabLayout.getTabAt(4), "集采完成" + num);
                        break;
                }
            } catch (Exception e) {//java.lang.NumberFormatException: For input string: ""
                LogUtil.e("FactoryJicaiActivity", e.toString());//没查到收据时返回空的时候类型转换异常
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideKeyboard();
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode ==STATUSTYPE){
                initData();
            }
        }
    }
}
